package com.chuangzhi.realm;

import com.chuangzhi.entity.Account;
import com.chuangzhi.service.AccountService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class AccountRealm extends AuthorizingRealm {

    @Autowired
    private AccountService accountService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前登录的用户信息 从shiro中
        Subject subject = SecurityUtils.getSubject();
        //因为认证中用户信息已保存 所以直接获取 getPrincipal
        Account account = (Account) subject.getPrincipal();

        //设置角色
        Set<String> roles = new HashSet<>();
        roles.add(account.getRole());
        //AuthorizationInfo 存储用户角色信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);


        //设置权限
        info.addStringPermission(account.getPerms());


        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    //controller接受 用户数据会跳转到这
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        Account account = accountService.findByUsername(token.getUsername());

        //不管判断是否成功 默认都会抛出异常 由Controller捕获异常
        if (account != null){
        //用户名自己判断
            //SimpleAuthenticationInfo 实现了密码判断(数据库密码查询account.getPassword()) 用户信息保存 等功能
            return new SimpleAuthenticationInfo(account,account.getPassword(),getName());
        }
        return null;
    }
}
